const path = require('path')
const fs = require('fs')
const WebSocket = require('ws')
const wss = new WebSocket.Server({
    port: 9998
})
const getFileJsonData = (filePath) => {
    // 根据文件路径读取内容
    return new Promise((resolve, reject) => {
        fs.readFile(filePath, 'utf-8', (error, data) => {
            if (error) {
                // 读取文件失败
                reject(error)
            } else {
                // 读取文件成功
                resolve(data)
            }
        })
    })
}
module.exports.listen = () => {
    wss.on('connection', client => {
        client.on('message', async msg => {
            let payload = JSON.parse(msg)
            const action = payload.action
            if (action === 'getData') {
                let filePath = '../data/' + payload.chartName + '.json'
                filePath = path.join(__dirname, filePath)
                const ret = await getFileJsonData(filePath)
                payload.data = ret
                client.send(JSON.stringify(payload))
            } else {
                wss.clients.forEach(client => {
                    client.send(msg)
                })
            }
        })
    })
}